package com.yunchao.library.socket.model.submit

import com.yunchao.library.socket.extensions.getString
import com.yunchao.library.socket.extensions.putString
import com.yunchao.library.socket.extensions.toReadOnlyBuffer
import com.yunchao.library.socket.utils.BufferPool
import com.yunchao.library.socket.utils.EncryptUtils
import com.yunchao.library.socket.utils.ValidationUtils
import java.nio.ByteBuffer
import java.nio.ByteOrder

data class SubmitRequest(
    val id: UInt,
    val fragment: UInt,
    val timestamp: ULong,
    val data: String,
    val operator: UInt,
    val auditor: UInt
) {


    fun toByteArray(): ByteArray {
        val dataBytes = data.encodeToByteArray()
        return EncryptUtils.encryptSHA1(
            BufferPool.use(28 + dataBytes.size) { buffer ->
                buffer.putInt(id.toInt())
                buffer.putInt(fragment.toInt())
                buffer.putLong(timestamp.toLong())
                buffer.putString(data)
                buffer.putInt(operator.toInt())
                buffer.putInt(auditor.toInt())
                buffer.array().copyOf(buffer.position())
            }
        )
    }

    companion object {

        fun fromByteArray(bytes: ByteArray): SubmitRequest {
            val buffer = bytes.toReadOnlyBuffer()
            return SubmitRequest(
                id = buffer.int.toUInt(),
                fragment = buffer.int.toUInt(),
                timestamp = buffer.long.toULong(),
                data = buffer.getString(),
                operator = buffer.int.toUInt(),
                auditor = buffer.int.toUInt(),
            )
        }
    }
}